#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# Project: spd-sxmcc
"""
@author: lyndon
@time Created on 2018/11/26 12:57
@desc
"""

import random
from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from spidermanager.setting import ip_pool_db
engine = create_engine(ip_pool_db)
Base = declarative_base()


class IpPool(Base):

    __tablename__ = 'ip_pool'

    ip_port = Column(String(30), primary_key=True)
    protocol = Column(String(10))
    get_time = Column(String(15))

    def __repr__(self):
        """  这个类似java的 toString方法 """
        return '%s(%r)' % (self.__class__.__name__, self.ip_port)

    def insert_one(self):
        try:
            Session = sessionmaker(bind=engine)
            session = Session()
            session.add(self)
            session.commit()
        except Exception as e:
            print('SQL Insert Exception', e)

    def select(self):
        Session = sessionmaker(bind=engine)
        session = Session()
        return session.query(IpPool).all()

    def truncate(self):
        try:
            Session = sessionmaker(bind=engine)
            session = Session()
            session.query(self).delete()
            session.commit()
        except Exception as e:
            print('Truncate Exception', e)

    def select_random_proxy(self):
        ip_pools = self.select()
        n = random.randint(1, len(ip_pools))
        proxy_ip_port = ip_pools[n].ip_port
        return proxy_ip_port

if __name__ == '__main__':
    # Base.metadata.create_all(engine)
    # Session = sessionmaker(bind=engine)
    # session = Session()
    # a = session.query(IpPool).all()
    # print(a)
    table = IpPool()
    proxy_ip_port = table.select_random_proxy()
    print(proxy_ip_port)
    # list_ip = table.select()
    # print(list_ip)
    # print(len(list_ip))
    # for ip in list_ip:
    #     print(ip.ip_port)
    # table.truncate()

